<template>
  <div class="divBox">
    <el-card
      class="box-card"
      shadow="never"
      :bordered="false"
      :body-style="{ padding: 0 }"
    >
      <div class="padding-add">
        <el-form ref="form" inline :model="tableFrom" @submit.native.prevent>
          <el-form-item label="选手名称：">
            <el-input
              v-model.trim="tableFrom.playerName"
              placeholder="请输入选手名称"
              class="selWidth"
              size="small"
              clearable
              @keyup.enter.native="getList(1)"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号：">
            <el-input
              v-model.trim="tableFrom.phone"
              placeholder="请输入手机号"
              class="selWidth"
              size="small"
              clearable
              @keyup.enter.native="getList(1)"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱：">
            <el-input
              v-model.trim="tableFrom.emailAccount"
              placeholder="请输入邮箱"
              class="selWidth"
              size="small"
              clearable
              @keyup.enter.native="getList(1)"
            ></el-input>
          </el-form-item>
          <el-form-item label="认证类型：">
            <el-select
              v-model="tableFrom.applyType"
              placeholder="请选择认证类型"
              class="selWidth"
              size="small"
              clearable
              @change="getList(1)"
            >
              <el-option :value="1" label="个人"></el-option>
              <el-option :value="2" label="企业"></el-option>
              <el-option :value="3" label="学生"></el-option>
              <el-option :value="-1" label="原创用户"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="small" @click="getList(1)">查询</el-button>
            <el-button size="small" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card mt14" :body-style="{ padding: '20px' }" shadow="never" :bordered="false">
      <el-table 
        v-loading="loading" 
        :data="tableData.data" 
        size="small"
        :scroll-x="true"
        style="width: 100%"
        :max-height="600"
      >
        <!-- 根据EmailUser实体类字段显示 -->
        <el-table-column prop="euserId" label="用户ID" min-width="80" />
        <el-table-column label="邮箱账号" min-width="180" prop="emailAccount" :show-overflow-tooltip="true" />
        <el-table-column label="用户头像" min-width="100">
          <template slot-scope="scope">
            <el-image 
              v-if="scope.row.avatar" 
              :src="scope.row.avatar" 
              style="width: 40px; height: 40px; border-radius: 50%;"
              :preview-src-list="[scope.row.avatar]"
            />
            <span v-else class="text-muted">无头像</span>
          </template>
        </el-table-column>
        <el-table-column label="选手名称" min-width="120" prop="playerName" :show-overflow-tooltip="true" />
        <el-table-column label="手机号" min-width="130" prop="phone" />
        <el-table-column label="创建时间" min-width="150" prop="createTime" />
        <el-table-column label="更新时间" min-width="150" prop="updateTime" />
        <el-table-column label="绑定状态" min-width="100" prop="isBind">
          <template slot-scope="scope">
            <el-tag 
              :type="scope.row.isBind === 1 ? 'success' : 'warning'"
              size="small"
            >
              {{ scope.row.isBind === 1 ? '已绑定' : '未绑定' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="认证类型" min-width="100" prop="applyType">
          <template slot-scope="scope">
            <el-tag 
              :type="getApplyTypeType(scope.row.applyType)"
              size="small"
            >
              {{ getApplyTypeText(scope.row.applyType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="国家" min-width="80" prop="country">
          <template slot-scope="scope">
            {{ getCountryText(scope.row.country) }}
          </template>
        </el-table-column>
        <el-table-column label="性别" min-width="80" prop="sex">
          <template slot-scope="scope">
            {{ getSexText(scope.row.sex) }}
          </template>
        </el-table-column>

        <el-table-column prop="address" fixed="right" width="80" label="操作">
          <template slot-scope="scope">
            <a @click="handleDetail(scope.row)">查看详情</a>
          </template>
        </el-table-column>
      </el-table>
      <div class="block-pagination">
        <el-pagination
          background
          :page-sizes="[20, 40, 60, 80]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @current-change="pageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog title="报名信息详情" :visible.sync="detailVisible" width="90%" :before-close="handleDetailClose">
      <div v-if="detailData" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item 
            v-for="key in allowedFields" 
            :key="key"
            :label="getFieldLabel(key)"
            :span="getFieldSpan(key)"
          >
            <template v-if="key === 'applyType'">
              <el-tag 
                :type="getApplyTypeType(detailData[key])"
                size="small"
              >
                {{ getApplyTypeText(detailData[key]) }}
              </el-tag>
            </template>
            <template v-else-if="key === 'sex'">
              {{ getSexText(detailData[key]) }}
            </template>
            <template v-else-if="key === 'isBind'">
              <el-tag 
                :type="detailData[key] === 1 ? 'success' : 'warning'"
                size="small"
              >
                {{ detailData[key] === 1 ? '已绑定' : '未绑定' }}
              </el-tag>
            </template>
            <template v-else-if="key === 'country'">
              {{ getCountryText(detailData[key]) }}
            </template>
            <template v-else-if="key === 'avatar'">
              <el-image 
                v-if="detailData[key]" 
                :src="detailData[key]" 
                style="width: 40px; height: 40px; border-radius: 50%;"
                :preview-src-list="[detailData[key]]"
              />
              <span v-else class="text-muted">无头像</span>
            </template>
            <template v-else-if="isImageField(key, detailData[key])">
              <el-image 
                v-if="detailData[key]" 
                :src="detailData[key]" 
                style="max-width: 100px; max-height: 100px;"
                :preview-src-list="[detailData[key]]"
              />
              <span v-else class="text-muted">无图片</span>
            </template>
            <template v-else>
              {{ formatFieldValue(key, detailData[key]) }}
            </template>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div slot="footer">
        <el-button @click="handleDetailClose">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// +---------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +---------------------------------------------------------------------
// | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
// +---------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +---------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +---------------------------------------------------------------------
import { checkPermi } from '@/utils/permission'; // 权限判断函数
import { applyInfoListApi, applyInfoDetailApi } from '@/api/applyInfo';

export default {
  name: 'ApplyInfo',
  data() {
    return {
      constants: this.$constants,
      tableFrom: {
        page: 1,
        limit: 20,
        playerName: '',
        phone: '',
        emailAccount: '',
        applyType: null,
      },
      loading: false,
      detailVisible: false,
      detailData: null,
      tableData: {
        data: [],
        total: 0,
      },
      // 允许在详情中显示的字段
      allowedFields: [
        'eUserId', 'emailAccount', 'avatar', 'playerName', 'phone', 
        'createTime', 'updateTime', 'isBind', 'applyType', 'country', 'sex'
      ],
    };
  },
  mounted() {
    console.log('报名信息页面已挂载');
    console.log('开始加载报名信息列表');
    this.getList(1);
  },
  methods: {
    checkPermi,
    // 重置表单
    resetForm() {
      this.tableFrom.playerName = '';
      this.tableFrom.phone = '';
      this.tableFrom.emailAccount = '';
      this.tableFrom.applyType = null;
      this.getList(1);
    },
    // 查看详情
    handleDetail(row) {
      console.log('查看详情，完整行数据:', row);
      console.log('所有字段:', Object.keys(row));
      console.log('eUserId:', row.eUserId);
      console.log('id:', row.id);
      console.log('euserId:', row.euserId); // 检查小写版本
      
      this.detailVisible = true;
      this.loading = true;
      
      // 尝试多种可能的字段名
      const userId = row.eUserId || row.euserId || row.id;
      console.log('使用的用户ID:', userId);
      
      if (!userId) {
        this.$message.error('无法获取用户ID，请检查数据结构');
        console.error('行数据中未找到用户ID字段，可用字段:', Object.keys(row));
        this.loading = false;
        return;
      }
      
      applyInfoDetailApi(userId)
        .then((res) => {
          this.detailData = res;
          this.loading = false;
        })
        .catch((err) => {
          console.error('获取详情失败:', err);
          this.loading = false;
        });
    },
    // 关闭详情弹窗
    handleDetailClose() {
      this.detailVisible = false;
      this.detailData = null;
    },

    // 列表
    getList(num) {
      this.loading = true;
      this.tableFrom.page = num ? num : this.tableFrom.page;
      
      // 构建请求参数，根据用户选择的认证类型传递 applyTypes
      const params = {
        ...this.tableFrom,
        applyTypes: this.tableFrom.applyType ? this.tableFrom.applyType.toString() : '0,1,2,3'  // 如果指定了认证类型就用指定的，否则查询所有类型
      };
      
      console.log('开始请求报名信息列表，参数：', params);
      
      // 调试token信息
      const token = this.$store.getters.token || sessionStorage.getItem('token');
      console.log('当前token：', token);
      
      applyInfoListApi(params)
        .then((res) => {
          console.log('报名信息列表请求成功：', res);
          this.tableData.data = res.list;
          this.tableData.total = res.total;
          this.loading = false;
        })
        .catch((error) => {
          console.error('报名信息列表请求失败：', error);
          this.loading = false;
        });
    },
    pageChange(page) {
      this.tableFrom.page = page;
      this.getList();
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val;
      this.getList();
    },
    
    
    // 获取认证类型文本
    getApplyTypeText(applyType) {
      const typeMap = {
        1: '个人',
        2: '企业',
        3: '学生',
        '-1': '原创用户'
      };
      return typeMap[applyType] || '未认证';
    },
    
    // 获取认证类型标签类型
    getApplyTypeType(applyType) {
      const typeMap = {
        1: 'primary',    // 个人 - 蓝色
        2: 'success',    // 企业 - 绿色
        3: 'warning',    // 学生 - 橙色
        '-1': 'info'     // 虚拟用户 - 灰色
      };
      return typeMap[applyType] || 'danger';  // 未认证 - 红色
    },
    
    
    // 获取性别文本
    getSexText(sex) {
      const sexMap = {
        0: '未知',
        1: '男',
        2: '女',
        3: '保密'
      };
      return sexMap[sex] || '未知';
    },
    
    // 获取国家文本
    getCountryText(country) {
      if (!country) return '未设置';
      
      const countryMap = {
        'CN': '中国',
        'OTHER': '其他'
      };
      
      return countryMap[country] || country;
    },
    
    
    // 获取字段标签 - 只显示EmailUser实体类中的字段
    getFieldLabel(key) {
      const labelMap = {
        eUserId: '用户ID',
        emailAccount: '邮箱账号',
        avatar: '用户头像',
        playerName: '选手名称',
        phone: '手机号',
        createTime: '创建时间',
        updateTime: '更新时间',
        isBind: '绑定状态',
        applyType: '认证类型',
        country: '国家',
        sex: '性别'
      };
      return labelMap[key] || key;
    },
    
    // 获取字段跨度 - 只显示EmailUser实体类中的字段
    getFieldSpan(key) {
      // 所有字段都占一列
      return 1;
    },
    
    // 判断是否为图片字段 - 只检查EmailUser实体类中的avatar字段
    isImageField(key, value) {
      if (!value || typeof value !== 'string') return false;
      
      // 只检查avatar字段
      if (key === 'avatar') {
        const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'];
        return imageExtensions.some(ext => value.toLowerCase().includes(ext)) || 
               value.includes('image') || 
               value.includes('photo') ||
               value.includes('picture');
      }
      
      return false;
    },
    
    // 格式化字段值
    formatFieldValue(key, value) {
      if (value === null || value === undefined) return '未设置';
      if (typeof value === 'boolean') return value ? '是' : '否';
      if (typeof value === 'object') return JSON.stringify(value);
      if (typeof value === 'string' && value.trim() === '') return '未设置';
      return value;
    },
    
  },
};
</script>

<style scoped lang="scss">
.detail-content {
  .extra-fields {
    h4 {
      margin-bottom: 15px;
      color: #303133;
    }
  }
}


.text-muted {
  color: #999;
  font-size: 12px;
}


// 表格样式优化
.el-table {
  .el-table__header {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }
  }
  
  .el-table__body {
    tr:hover {
      background-color: #f5f7fa;
    }
  }
}

// 表格列样式
.table-column {
  &.text-center {
    text-align: center;
  }
  
  &.text-right {
    text-align: right;
  }
}

// 长文本显示优化
.long-text {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style> 